package com.leo;

import javafx.geometry.Pos;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;

/**
 * @ClassName MyTableCell
 * @Description
 * @Author wangss
 * @date 2020.06.14 00:36
 * @Version 1.0
 */
public class MyTableCell<S, T> extends TableCell<S, T> {

    private String object;
    private Class clazz;

    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);

        if (!empty) {

            HBox hBox = new HBox();
            hBox.setAlignment(Pos.CENTER);
            if (Boolean.class.isAssignableFrom(item.getClass())) {

                CheckBox checkBox = new CheckBox();
                checkBox.setSelected((Boolean) item);
                clazz = Boolean.class;
                hBox.getChildren().add(checkBox);

            } else if (Integer.class.isAssignableFrom(item.getClass())) {
                Label label = new Label(item.toString());
                object = item.toString();
                // 这里可以暂存数据
                this.setUserData(item);
                clazz = Integer.class;
                hBox.getChildren().add(label);
            } else if (String.class.isAssignableFrom(item.getClass())) {
                Label label = new Label((String) item);
                clazz = String.class;
                hBox.getChildren().add(label);
            }
            this.setGraphic(hBox);
        }
    }

    @Override
    public void startEdit() {
        super.startEdit();

        if (Integer.class.isAssignableFrom(clazz)) {
            HBox hBox = new HBox();
            hBox.setAlignment(Pos.CENTER);

            TextField tf = new TextField();
//            tf.setText(object);

            tf.setText(this.getUserData().toString());

            hBox.getChildren().add(tf);

            this.setGraphic(hBox);

            tf.setOnKeyPressed(event -> {
                if (event.getCode() == KeyCode.ENTER) {
                    String text = tf.getText();
                    Integer parseInt = Integer.parseInt(text);
                    this.commitEdit((T) parseInt);
                }
            });
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        if (Integer.class.isAssignableFrom(clazz)) {
            HBox hBox = new HBox();
            hBox.setAlignment(Pos.CENTER);
            Label label = new Label(object);
            hBox.getChildren().add(label);
            this.setGraphic(hBox);
        }
    }
}
